﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace mtg_trader.GUI
{
    public static class UrlDownloader
    {

        public static string GetHtml(string uri, string fileName)
        {

            if (string.IsNullOrEmpty(fileName)) return string.Empty;

            var directory = Path.GetDirectoryName(fileName);

            if (string.IsNullOrEmpty(directory)) return string.Empty;

            if (!Directory.Exists(directory))
            {
                Debug.Print("Creating new directory: {0}", directory);
                Directory.CreateDirectory(directory);
            }

            Debug.Print("Checking for file...");
            if (File.Exists(fileName))
            {
                Debug.Print("File found");
                using (var streamReader = new StreamReader(fileName))
                {
                    return streamReader.ReadToEnd();
                }
            }

            // Should ensure that webClient.Encoding = Encoding.UTF8
            Debug.Print("No file found, attempting download");
            try
            {
                using (var webClient = new WebClient())
                {
                    webClient.Encoding = Encoding.UTF8;
                    var result = webClient.DownloadString(uri);
                    using (var streamWriter = new StreamWriter(fileName))
                    {
                        streamWriter.Write(result);
                        Debug.Print("Created new file {0}", fileName);
                    }
                    return result;
                }
            }
            catch (Exception exception)
            {
                Debug.Print("Encountered an exception: {0}", exception.Message);
                Debug.Print("Url: {0}", uri);
                using (var streamWriter = new StreamWriter(Path.Combine(directory, "errors.txt")))
                {
                    streamWriter.WriteLine("{0} Encountered an exception: {1}", DateTime.Now, exception.Message);
                    streamWriter.WriteLine("{0} Url: {1}", DateTime.Now, uri);
                }
                Debug.Print("Returning 'Empty String'");
                return string.Empty;
            }

        }

    }
}
